package com.example.demo.user.controller;

import com.example.demo.user.entity.WxSessionResponse;
import com.example.demo.util.result.Result;
import lombok.Data;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
@RequestMapping("/wechat")
public class WeChatController {

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    @Value("${wechat.redirect_uri}")
    private String redirectUri;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/callback")
    public ResponseEntity<String> callback(@RequestParam String code) {
        // 1. 通过code获取access_token和openid
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid +
                "&secret=" + secret +
                "&code=" + code +
                "&grant_type=authorization_code";

        ResponseEntity<String> response = restTemplate.getForEntity(tokenUrl, String.class);
        JSONObject tokenResponse = new JSONObject(response.getBody());

        String accessToken = tokenResponse.getString("access_token");
        String openid = tokenResponse.getString("openid");

        // 2. 获取用户信息
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken +
                "&openid=" + openid;

        ResponseEntity<String> userInfoResponse = restTemplate.getForEntity(userInfoUrl, String.class);
        JSONObject userInfo = new JSONObject(userInfoResponse.getBody());

        // 3. 处理用户信息（如保存到数据库）
        String nickname = userInfo.getString("nickname");
        String headimgurl = userInfo.getString("headimgurl");

        // 4. 完成登录逻辑（如生成JWT）
        String jwtToken = generateJwtToken(openid);

        return ResponseEntity.ok(jwtToken);
    }

    private String generateJwtToken(String openid) {
        // 生成JWT的逻辑
        return "your_jwt_token";
    }

    @PostMapping("/miniprogram-login")
    public Result<WxSessionResponse> miniProgramLogin(@RequestBody Map<String, String> params) {
        String code = params.get("code");
        String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?" +
                        "appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appid, secret, code);
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        JSONObject userInfo = new JSONObject(response.getBody());
        String session_key = userInfo.getString("session_key");
        String openid = userInfo.getString("openid");
        WxSessionResponse wxSessionResponse = new WxSessionResponse();
        wxSessionResponse.setSession_key(session_key);
        wxSessionResponse.setOpenid(openid);
        // 处理用户逻辑...
        return Result.ok(wxSessionResponse);
    }


}
